//
//  BIDModifyView.m
//  theFifth
//
//  Created by 邵瑞 on 13-6-4.
//
//

#import "BIDModifyView.h"
//
#import "TheProjectCell.h"
#import "TreeViewNode.h"
#import "BIDTypesManager.h"
#import "BIDATypes.h"
#import "BIDBillsLookoverManager.h"
@interface BIDModifyView ()
{
       BIDTypesManager * typeManager;
       NSMutableArray * mainTypes;
       UITextField * textField;
       NSString * celllable;
        NSInteger typeID;
       NSMutableArray *nodes;
       TreeViewNode *secondLevelNode1;
       TreeViewNode * firstLevelNode1;
       NSString *stringMainType;
       
       NSString *stringSubType;
       NSInteger mianTypeID;
       NSInteger subTypeID;
}
@property(strong,nonatomic) NSMutableArray *extendSection;
///////////////////
@property (nonatomic, retain) NSMutableArray *displayArray;

- (void)expandCollapseNode:(NSNotification *)notification;

- (void)fillDisplayArray;
- (void)fillNodeWithChildrenArray:(NSArray *)childrenArray;

- (void)fillNodesArray;
- (NSArray *)fillChildrenForNode;

- (IBAction)expandAll:(id)sender;
- (IBAction)collapseAll:(id)sender;
@end

@implementation BIDModifyView
@synthesize tableviews;
@synthesize extendSection;
@synthesize displayArray;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
       self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
       if (self) {
       // Custom initialization
       }
       return self;
}
-(void)viewWillAppear:(BOOL)animated
{
//       self.navigationController.navigationBarHidden = NO;
//        UIBarButtonItem *itern=  [[UIBarButtonItem alloc] initWithTitle:@"删除ddd" style:UIBarButtonSystemItemDone target:self action:@selector(tableViewEdit:)];
//       if (self.tabBarController.navigationItem.rightBarButtonItem==nil)
//       {
//           self.tabBarController.navigationItem.rightBarButtonItem=itern;
//
//       }





}
-(void)switchControl:(id)sender
{
       UISegmentedControl *con=sender;
       switch (con.selectedSegmentIndex)
       {
              case 0:
              [self modifyTypeOrSubType];

              con.hidden=YES;
              con.selectedSegmentIndex=-1;
              self.subTypeText.text=nil;
              self.mianTypetext.text=nil;
              break;
              case 1:
              //  [self addTypeOrSubTypes:nil];
              [self addTypeOrSubType:nil];
              con.hidden=YES;
              con.selectedSegmentIndex=-1;
              self.subTypeText.text=nil;
              self.mianTypetext.text=nil;


       default:
       break;



       }

}

-(void)viewDidAppear:(BOOL)animated
{

     self.navigationController.navigationBarHidden= NO;
}
-(void)viewWillDisappear:(BOOL)animated
{
       UISegmentedControl * segment = (UISegmentedControl *)[self.navigationController.navigationBar viewWithTag:2];
       [segment removeFromSuperview];

}
- (void)viewDidLoad
{
    [super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"manageType.png"]];
       self.subTypeText.delegate=self;
       self.mianTypetext.delegate = self;
      typeManager= [BIDTypesManager shareTypesManager];
       mainTypes = [typeManager DatabaseHadTypes];
       self.extendSection=[[NSMutableArray alloc] init];
       [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(expandCollapseNode:) name:@"ProjectTreeNodeButtonClicked" object:nil];

    [self fillNodesArray];
    [self fillDisplayArray];
    [self.tableviews reloadData];

            // Do any additional setup after loading the view from its nib.
}




#pragma
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
       [tableviews release];
       [_mianTypetext release];
    [_subTypeText release];
            [super dealloc];
}
- (void)viewDidUnload
{
       [[NSNotificationCenter defaultCenter]removeObserver:self];

       [tableviews release];
[self setTableviews:nil];
       [self setMianTypetext:nil];
       [self setTableviews:nil];
    [self setSubTypeText:nil];
    [super viewDidUnload];

}


-(void)fillDisplayArray
{
       self.displayArray = [[NSMutableArray alloc]init];
       for (TreeViewNode *node in nodes)
       {
              [self.displayArray addObject:node];
              if (node.isExpanded==NO)
              {
              [self fillNodeWithChildrenArray:node.nodeChildren];
              }
       }

}

#pragma TableView DataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
       return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.displayArray.count;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
              static NSString *CellIdentifier = @"treeNodeCell";
           UINib *nib = [UINib nibWithNibName:@"ProjectCell" bundle:nil];
           [tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
           
           TheProjectCell *cell = (TheProjectCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
           
           TreeViewNode *node = [self.displayArray objectAtIndex:indexPath.row];
           cell.treeNode = node;
           cell.cellLabel.text = node.nodeObject;
           cell.contentView.backgroundColor=[UIColor lightGrayColor];
              cell.selectionStyle  = UITableViewCellSelectionStyleGray;
           if (node.isExpanded)
            {
              
               [cell setTheButtonBackgroundImage:[UIImage imageNamed:@"Close"] andYearCount:nil];
           }
           else {
               [cell setTheButtonBackgroundImage:[UIImage imageNamed:@"Open"] andYearCount:nil];
           }
           [cell setNeedsDisplay];

           return cell;

}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

       NSString * string = [self.displayArray objectAtIndex:indexPath.row];

               if ([self.displayArray containsObject:string])
              {
                     [self.displayArray removeObject:string];
              [self reference];
              }


       
}
#pragma TableView Delegate
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
       return @"删除";
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
       return YES;

}

//点击某一行要做的事TableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{        
                     
       for (TreeViewNode *node in nodes)
       {

       if (node.isExpanded==NO)
       {

              self.mianTypetext.text = node.nodeObject;
              stringMainType = node.nodeObject;
              mianTypeID = [typeManager selectTypeid:stringMainType];
              TreeViewNode * ss = [self.displayArray objectAtIndex:indexPath.row];
              stringSubType = ss.nodeObject;
              subTypeID = [typeManager selectSubTypeid:stringSubType];
              NSLog(@"%@==》》%@－－>%d",node.nodeObject,ss.nodeObject,indexPath.row);
                     self.subTypeText.text = ss.nodeObject;
              
              }
   }
    
    [self segmentController];
//     UISegmentedControl * segment = (UISegmentedControl *)[self.navigationController.navigationBar viewWithTag:2];
//    
//    
//    if ([self.navigationController.navigationBar.subviews containsObject:segment]) {
//        if (segment.hidden)
//         {
//            segment.hidden=NO;
//            segment.selectedSegmentIndex=-1;
//        }
//    }
//    else
//    {
//    UISegmentedControl *segcon=[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"更新类别",@"新增类别", nil]];
//    segcon.tintColor=[UIColor grayColor];
//    segcon.segmentedControlStyle=1;
//    segcon.tag =2;
//    segcon.frame = CGRectMake(100, 3, 180, 35);
//    [segcon addTarget:self action:@selector(switchControl:) forControlEvents:UIControlEventValueChanged];
//        [self.navigationController.navigationBar addSubview:segcon];}

    
        
}

-(void)fillNodesArray
{
       nodes=[[NSMutableArray alloc] init];
       BIDATypes * bis = [[BIDATypes alloc]init];
       for (int i =0;i<mainTypes.count; i++)
       {
              firstLevelNode1= [[TreeViewNode alloc] init];
              firstLevelNode1.nodeLevel = 0;
              firstLevelNode1.isExpanded = YES;
              bis.typeId = [[mainTypes objectAtIndex:i] integerValue];
              typeID = bis.typeId;
              NSString * typename = [typeManager selectTypeName:bis.typeId];
              firstLevelNode1.nodeObject = typename;
              firstLevelNode1.nodeChildren = [[self fillChildrenForNode] mutableCopy];
              [nodes addObject:firstLevelNode1];

       }
}
-(NSArray *)fillChildrenForNode
{
       NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
       NSMutableArray * array =[typeManager listOfSubTypeInMainType:typeID];
       for (BIDATypes * bis in array)
        {
              secondLevelNode1 = [[TreeViewNode alloc]init];
              secondLevelNode1.nodeLevel = 1;
              NSString * subtypestr = [typeManager selectSubTypeName:bis.subTypeId];
              secondLevelNode1.nodeObject = subtypestr;
              [childrenArray addObject:secondLevelNode1];

       }

       return childrenArray;

}


-(void)expandCollapseNode:(NSNotification *)notification
{
       mainTypes = [typeManager DatabaseHadTypes];
       [self fillDisplayArray];
    [self.tableviews reloadData];



}
//展开时
-(void)fillNodeWithChildrenArray:(NSArray *)childrenArray
{
       
  for (TreeViewNode *node in childrenArray)
   {
        [self.displayArray addObject:node];
        if (node.isExpanded==NO)
        {
            [self fillNodeWithChildrenArray:node.nodeChildren];
//                   [self.tableviews reloadData];

        }
    }


}
-(IBAction)collapseAll:(id)sender
{

       for (TreeViewNode *treeNode in nodes)
       {
              treeNode.isExpanded = NO;
       }
       [self fillDisplayArray];
       [self.tableviews reloadData];

}
-(IBAction)expandAll:(id)sender
{

   [self fillNodesArray];
    [self fillDisplayArray];
    [self.tableviews reloadData];

}
- (void)tableViewEdit:(id)sender
{
//   [self.tableviews setEditing:!self.tableviews.editing animated:YES];
    if (self.tableviews.editing)
      {
  self.tableviews.editing=NO;
      }
     else
     {self.tableviews.editing=YES;};
}

- (IBAction)keydisapper:(id)sender
{
       [self.mianTypetext resignFirstResponder];
       [self.subTypeText resignFirstResponder];
       [sender resignFirstResponder];
}

- (IBAction)deleteType:(id)sender
{
      // [self.tableviews setEditing:!self.tableviews.editing animated:YES];
              if (!self.tableviews.editing)
              {
                     self.tableviews.editing=YES;
              }
              else
              {
                     self.tableviews.editing=NO;
              }

}
//-(void)addTypeOrSubTypes:(UIView *)View
//{
//        BIDATypes *update = [[BIDATypes alloc] init];
//       NSString * mainTypestr  = self.mianTypetext.text;
//       NSString * subTypestr = self.subTypeText.text;
//       update.type=mainTypestr;
//       update.subType = subTypestr;
//       update.typeId = mianTypeID;
//       update.subTypeId = subTypeID;
//
//       BOOL addtype = [typeManager addAtypeOrSubType:mainTypestr OrSubType:nil];
//      
//
//       if (addtype)
//       {
//       NSLog(@"chenggong");
//       }
//       mainTypes = [typeManager DatabaseHadTypes];
//    [self fillNodesArray];//add child
//    [self displayArray];
//    [self fillDisplayArray];
//       [self.tableviews reloadData];
//
//}
- (void)addTypeOrSubType:(id)sender
{
       if (self.subTypeText.text.length!=0&&self.mianTypetext.text.length==0)
       {
              UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"请输入主类别" delegate:self cancelButtonTitle:@"明白了,取消" otherButtonTitles:nil];
              alert.backgroundColor = [UIColor greenColor];

              [alert show];
              [alert release];
       }
              
       else if (self.mianTypetext.text.length==0&&self.subTypeText.text.length
       ==0)
       {
              UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"请输入类别或" delegate:self cancelButtonTitle:@"明白了,取消" otherButtonTitles:nil];
              alert.backgroundColor = [UIColor greenColor];

              [alert show];
              [alert release];
       }
       else if (self.mianTypetext.text.length!=0 && self.subTypeText.text.length==0)
       {
              BIDATypes *addSubType = [[BIDATypes alloc] init];
              
              NSString * mainTypestr  = self.mianTypetext.text;
              NSString * subTypestr = self.subTypeText.text;
              addSubType.type=stringMainType;//主
              addSubType.subType = stringSubType;//子
              addSubType.typeId = mianTypeID;
              addSubType.subTypeId = subTypeID;
              BOOL addtype = [typeManager addTypeOSubType:addSubType addAtypeOrSubType:mainTypestr OrSubType:subTypestr];//addAtypeOrSubType:mainTypestr OrSubType:stringSubType
             

              if (addtype)
              {
                     NSLog(@"chenggong");
              }

              [self reference];
       }

       else if(self.mianTypetext.text.length!=0 && self.subTypeText.text.length!=0)
       {
       

              BIDATypes *addSubType = [[BIDATypes alloc] init];
              
              NSString * mainTypestr  = self.mianTypetext.text;
              NSString * subTypestr = self.subTypeText.text;
              addSubType.type=stringMainType;//主
              addSubType.subType = stringSubType;//子
              addSubType.typeId = mianTypeID;
              addSubType.subTypeId = subTypeID;
              BOOL addtype = [typeManager addTypeOSubType:addSubType addAtypeOrSubType:mainTypestr OrSubType:subTypestr];//addAtypeOrSubType:mainTypestr OrSubType:stringSubType
             

              if (addtype)
              {
                     NSLog(@"chenggong");
              }

              [self reference];
       }


}
-(void)modifyTypeOrSubType
{

       if (self.mianTypetext.text.length==0&&self.subTypeText.text.length!=0)
              {
                     
                     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"更新,请选择主类别" delegate:self cancelButtonTitle:@"我明白了" otherButtonTitles:nil];
                     alert.backgroundColor = [UIColor brownColor];
                     [alert show];
                     [alert release];
       
              }
             else if (self.mianTypetext.text.length!=0&&self.subTypeText.text.length==0)
       {

       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"请输选子类别再更新,如果需要新增,请点击新增" delegate:self cancelButtonTitle:@"我明白" otherButtonTitles:nil];
                     alert.backgroundColor = [UIColor purpleColor];

              [alert show];
              [alert release];
       }
       else if (self.mianTypetext.text.length==0&& self.mianTypetext.text.length==0 )
       {
               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"没有主类别信息,不能更新,请输选主择类别" delegate:self cancelButtonTitle:@"我明白" otherButtonTitles:nil];
                     alert.backgroundColor = [UIColor purpleColor];

              [alert show];
              [alert release];
       }
       else if(self.mianTypetext.text.length!=0 && self.subTypeText.text.length!=0)
       {

      
              BIDATypes *Before = [[BIDATypes alloc] init];
              Before.type=stringMainType;
              Before.subType= stringSubType;
              Before.typeId = mianTypeID;
              Before.subTypeId = subTypeID;
              BIDATypes *update = [[BIDATypes alloc] init];
              NSString * mainTypestr  = self.mianTypetext.text;
              NSString * subTypestr = self.subTypeText.text;
                            update.type=mainTypestr;
              update.subType = subTypestr;
              update.typeId = mianTypeID;
              update.subTypeId = subTypeID;
              BOOL updateTypeOrSub = [typeManager updataTheTypeOrSubType:update andBeforeType:Before];
              if (updateTypeOrSub==YES)
              {
                     NSLog(@"ssss=======");
              }

           [self reference];
 }

       }
-(void)reference
{
       mainTypes = [typeManager DatabaseHadTypes];

       [self fillNodesArray];
       [self displayArray];
       [self fillDisplayArray];
       [self.tableviews reloadData];

}
-(void)segmentController
{
       UISegmentedControl * segment = (UISegmentedControl *)[self.navigationController.navigationBar viewWithTag:2];
       if ([self.navigationController.navigationBar.subviews containsObject:segment]) {
       if (segment.hidden)
       {
              segment.hidden=NO;
              segment.selectedSegmentIndex=-1;
       }
       }
       else
       {
              UISegmentedControl *segcon=[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"更新类别",@"新增类别", nil]];
              segcon.tintColor=[UIColor grayColor];
              segcon.segmentedControlStyle=1;
              segcon.tag =2;
              segcon.frame = CGRectMake(100, 3, 180, 35);
              [segcon addTarget:self action:@selector(switchControl:) forControlEvents:UIControlEventValueChanged];
              [self.navigationController.navigationBar addSubview:segcon];
        }


}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
     
            [self segmentController];

}
@end
